//
//  FFHomeController.m
//  FFAllProject
//
//  Created by ios on 2017/9/11.
//  Copyright © 2017年 lf. All rights reserved.
//

#import "FFHomeController.h"
#import <Speech/Speech.h>
#import <AVFoundation/AVFoundation.h>


@interface FFHomeController ()<SFSpeechRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;

// 录音相关
@property (strong, nonatomic) SFSpeechRecognizer *speechRecognizer;
@property (strong, nonatomic) AVAudioEngine *audioEngine;
@property (strong, nonatomic) SFSpeechRecognitionTask *recognitionTask;
@property (strong, nonatomic) SFSpeechAudioBufferRecognitionRequest *recognitionRequest;


@end

@implementation FFHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _recordBtn.enabled = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    __weak typeof(self) weakSelf = self;
    [SFSpeechRecognizer  requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                    weakSelf.recordBtn.enabled = NO;
                    [weakSelf.recordBtn setTitle:@"语音识别未授权" forState:UIControlStateDisabled];
                    break;
                case SFSpeechRecognizerAuthorizationStatusDenied:
                    weakSelf.recordBtn.enabled = NO;
                    [weakSelf.recordBtn setTitle:@"用户未授权使用语音识别" forState:UIControlStateDisabled];
                    break;
                case SFSpeechRecognizerAuthorizationStatusRestricted:
                    weakSelf.recordBtn.enabled = NO;
                    [weakSelf.recordBtn setTitle:@"语音识别在这台设备上受到限制" forState:UIControlStateDisabled];
                    
                    break;
                case SFSpeechRecognizerAuthorizationStatusAuthorized:
                    weakSelf.recordBtn.enabled = YES;
                    [weakSelf.recordBtn setTitle:@"开始录音" forState:UIControlStateNormal];
                    break;
                    
                default:
                    break;
            }
            
        });
    }];

}

- (IBAction)recordAction:(UIButton *)sender {
    
    if (self.audioEngine.isRunning) {
        
        [self.audioEngine stop];
        if (_recognitionRequest) {
            [_recognitionRequest endAudio];
        }
        
        self.recordBtn.enabled = NO;
        [self.recordBtn setTitle:@"正在停止..." forState:UIControlStateDisabled];
    } else {
        
        [self startRecording];
        [self.recordBtn setTitle:@"停止录音" forState:UIControlStateNormal];
    }
}

- (void)startRecording
{
    if (_recognitionTask) {
        
        [_recognitionTask cancel];
        _recognitionTask = nil;
    }
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error;
    [audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
    NSParameterAssert(!error);
    [audioSession setMode:AVAudioSessionModeMeasurement error:&error];
    NSParameterAssert(!error);
    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
    NSParameterAssert(!error);
    
    _recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
    AVAudioInputNode *inputNode = self.audioEngine.inputNode;
    NSAssert(inputNode, @"录入设备没有准备好");
    NSAssert(_recognitionRequest, @"请求初始化失败");
    _recognitionRequest.shouldReportPartialResults = YES;
    __weak typeof(self) weakSelf = self;
    
    NSLog(@"speechRecognizer = %@", self.speechRecognizer);
    _recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:_recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        BOOL isFinal = NO;
        
        NSLog(@"resule = %@", result);
        if (result) {
            
            NSLog(@"dddd =%@", result.bestTranscription.formattedString);
            strongSelf.resultLabel.text = result.bestTranscription.formattedString;
            isFinal = result.isFinal;
        }
        
        if (error || isFinal) {
            
            [self.audioEngine stop];
            [inputNode removeTapOnBus:0];
            strongSelf.recognitionTask = nil;
            strongSelf.recognitionRequest = nil;
            strongSelf.recordBtn.enabled = YES;
            [strongSelf.recordBtn setTitle:@"开始录音" forState:UIControlStateNormal];
        }
    }];
    
    AVAudioFormat *recordingFormate = [inputNode outputFormatForBus:0];
    //在添加tap之前先移除上一个  不然有可能报"Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio',"之类的错误
    [inputNode removeTapOnBus:0];
    [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormate block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf.recognitionRequest) {
            
            [strongSelf.recognitionRequest appendAudioPCMBuffer:buffer];
        }
    }];
    
    [self.audioEngine prepare];
    [self.audioEngine startAndReturnError:&error];
    NSParameterAssert(!error);
    self.resultLabel.text = @"正在录音...";
}

#pragma mark - lazyload
- (AVAudioEngine *)audioEngine
{
    if (!_audioEngine) {
        
        _audioEngine = [[AVAudioEngine alloc] init];
    }
    
    return _audioEngine;
}

- (SFSpeechRecognizer *)speechRecognizer
{
    if (!_speechRecognizer) {
        
        // 为语音识别设置语言, 这里是中文
        NSLocale *local = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        _speechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:local];
        _speechRecognizer.delegate = self;
    }
    return _speechRecognizer;
}

#pragma mark - SFSpeechRecognizerDelegate
- (void)speechRecognizer:(SFSpeechRecognizer *)speechRecognizer availabilityDidChange:(BOOL)available
{
    if (available) {
        
        self.recordBtn.enabled = YES;
        [self.recordBtn setTitle:@"开始录音" forState:UIControlStateNormal];
    } else {
        
        self.recordBtn.enabled = NO;
        [self.recordBtn setTitle:@"语音识别不可用" forState:UIControlStateDisabled];
    }
}

//- (void)viewDidAppear:(BOOL)animated{
//    [super viewDidAppear:animated];
//    __weak typeof(self) weakSelf = self;
//    [SFSpeechRecognizer  requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            switch (status) {
//                case SFSpeechRecognizerAuthorizationStatusNotDetermined:
//                    weakSelf.recordBtn.enabled = NO;
//                    [weakSelf.recordBtn setTitle:@"语音识别未授权" forState:UIControlStateDisabled];
//                    break;
//                case SFSpeechRecognizerAuthorizationStatusDenied:
//                    weakSelf.recordBtn.enabled = NO;
//                    [weakSelf.recordBtn setTitle:@"用户未授权使用语音识别" forState:UIControlStateDisabled];
//                    break;
//                case SFSpeechRecognizerAuthorizationStatusRestricted:
//                    weakSelf.recordBtn.enabled = NO;
//                    [weakSelf.recordBtn setTitle:@"语音识别在这台设备上受到限制" forState:UIControlStateDisabled];
//                    
//                    break;
//                case SFSpeechRecognizerAuthorizationStatusAuthorized:
//                    weakSelf.recordBtn.enabled = YES;
//                    [weakSelf.recordBtn setTitle:@"开始录音" forState:UIControlStateNormal];
//                    break;
//                    
//                default:
//                    break;
//            }
//            
//        });
//    }];
//}
//- (IBAction)recordAction:(UIButton *)sender {
//    if (self.audioEngine.isRunning) {
//        [self.audioEngine stop];
//        if (_recognitionRequest) {
//            [_recognitionRequest endAudio];
//        }
//        self.recordBtn.enabled = NO;
//        [self.recordBtn setTitle:@"正在停止" forState:UIControlStateDisabled];
//        
//    }
//    else{
//        [self startRecording];
//        [self.recordBtn setTitle:@"停止录音" forState:UIControlStateNormal];
//        
//    }
//}
//- (void)startRecording{
//    if (_recognitionTask) {
//        [_recognitionTask cancel];
//        _recognitionTask = nil;
//    }
//    
//    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//    NSError *error;
//    [audioSession setCategory:AVAudioSessionCategoryRecord error:&error];
//    NSParameterAssert(!error);
//    [audioSession setMode:AVAudioSessionModeMeasurement error:&error];
//    NSParameterAssert(!error);
//    [audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];
//    NSParameterAssert(!error);
//    
//    _recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
//    AVAudioInputNode *inputNode = self.audioEngine.inputNode;
//    NSAssert(inputNode, @"录入设备没有准备好");
//    NSAssert(_recognitionRequest, @"请求初始化失败");
//    _recognitionRequest.shouldReportPartialResults = YES;
//    __weak typeof(self) weakSelf = self;
//    _recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:_recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
//        __strong typeof(weakSelf) strongSelf = weakSelf;
//        BOOL isFinal = NO;
//        if (result) {
//            strongSelf.resultLabel.text = result.bestTranscription.formattedString;
//            isFinal = result.isFinal;
//        }
//        if (error || isFinal) {
//            [self.audioEngine stop];
//            [inputNode removeTapOnBus:0];
//            strongSelf.recognitionTask = nil;
//            strongSelf.recognitionRequest = nil;
//            strongSelf.recordBtn.enabled = YES;
//            [strongSelf.recordBtn setTitle:@"开始录音" forState:UIControlStateNormal];
//        }
//        
//    }];
//    
//    AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
//    //在添加tap之前先移除上一个  不然有可能报"Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio',"之类的错误
//    [inputNode removeTapOnBus:0];
//    [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
//        __strong typeof(weakSelf) strongSelf = weakSelf;
//        if (strongSelf.recognitionRequest) {
//            [strongSelf.recognitionRequest appendAudioPCMBuffer:buffer];
//        }
//    }];
//    
//    [self.audioEngine prepare];
//    [self.audioEngine startAndReturnError:&error];
//    NSParameterAssert(!error);
//    self.resultLabel.text = @"正在录音。。。";
//}
//#pragma mark - lazyload
//- (AVAudioEngine *)audioEngine{
//    if (!_audioEngine) {
//        _audioEngine = [[AVAudioEngine alloc] init];
//    }
//    return _audioEngine;
//}
//- (SFSpeechRecognizer *)speechRecognizer{
//    if (!_speechRecognizer) {
//        //腰围语音识别对象设置语言，这里设置的是中文
//        NSLocale *local =[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
//        
//        _speechRecognizer =[[SFSpeechRecognizer alloc] initWithLocale:local];
//        _speechRecognizer.delegate = self;
//    }
//    return _speechRecognizer;
//}
//#pragma mark - SFSpeechRecognizerDelegate
//- (void)speechRecognizer:(SFSpeechRecognizer *)speechRecognizer availabilityDidChange:(BOOL)available{
//    if (available) {
//        self.recordBtn.enabled = YES;
//        [self.recordBtn setTitle:@"开始录音" forState:UIControlStateNormal];
//    }
//    else{
//        self.recordBtn.enabled = NO;
//        [self.recordBtn setTitle:@"语音识别不可用" forState:UIControlStateDisabled];
//    }
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
